﻿using System;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Web;
using Infrastructure;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json;

namespace XieAuth.Mvc.Filters
{
    public class MvcRequestLogFilter : ActionFilterAttribute
    {
        public MvcRequestLogFilter()
        {
           
        }
       

        public override void OnActionExecuting(ActionExecutingContext context)
        {
         
            string path = Path.Combine(Directory.GetCurrentDirectory(), "Log");
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            string fileName = Path.Combine(path, $"RequestLog-{DateTime.Now.ToString("yyyyMMdd")}.log");
            using (FileStream fs = new FileStream(fileName, FileMode.Append, FileAccess.Write, FileShare.ReadWrite))
            {
                using (StreamWriter sw = new StreamWriter(fs))
                {
                    string body = "";
                    Stream stream = context.HttpContext.Request.Body;                  

                    byte[] buffer = new byte[context.HttpContext.Request.ContentLength??0];
                    stream.Read(buffer, 0, buffer.Length);
                    body=Encoding.Default.GetString(buffer);
                    
                    string exceptionContent =
                        $"{DateTime.Now.ToString()}\r\n" +
                        $"请求方法：{context.HttpContext.Request.Method}\r\n" +
                        $"请求Url：{context.HttpContext.Request.GetEncodedPathAndQuery()}\r\n"+
                        $"请求头x-token：{context.HttpContext.Request.Headers["x-token"]}\r\n"+
                        $"请求Cookies：{context.HttpContext.Request.Cookies.ToJson()}\r\n"+
                        $"请求ContentType：{context.HttpContext.Request.ContentType}\r\n" +                      
                        $"请求体：{body}\r\n";
                    sw.WriteLine(exceptionContent);
                }

            }
            
        }

        public override void OnActionExecuted(ActionExecutedContext context)
        {
            
        }
    }
}